#!/usr/bin/python2
# -*- coding: utf8 -*-
from PyQt4 import QtCore, QtSql
from models.Job  import Job
from utils.log import log
from utils.exceptions.DataBaseException import DataBaseException

class LocalStorage(QtCore.QObject):
    db = QtSql.QSqlDatabase('QSQLITE')
    listeners = []

    def __init__(self, parent=None):
        QtCore.QObject.__init__(self, parent)
        self.db.setDatabaseName('data/sqlite_database')
        ok = self.db.open()
        self.db.exec_("PRAGMA encoding = \"UTF-8\"");

        log.info("self.db.open()=" + str(ok))

        self.execSqlFromFile("data/dataStruct.sql")
        #self.execSqlFromFile("data/testData.sql")
        self.dump()


    def execSqlFromFile(self, fileName):
        query = QtSql.QSqlQuery(self.db)
        f = open(fileName)
        for line in f:
            ok = query.exec_(line)
            log.debug("last query: " + str(ok) + ": " + query.lastError().text() + " (" + query.lastQuery() + ")")
        f.close()

    def getJobs(self, fromTime = 0, toTime = 9999999999, limit = 9999):
        q = QtSql.QSqlQuery(self.db)
        q.prepare("SELECT * FROM `jobs` WHERE jobs.startTime >= :fromTime AND jobs.startTime < :toTime LIMIT :limit;")
        q.bindValue(":fromTime", fromTime)
        q.bindValue(":toTime", toTime)
        q.bindValue(":limit", limit)
        ok = q.exec_()
        log.debug("last query: " + str(ok) + ": " + q.lastError().text() + " (" + q.lastQuery() + "), size=" + str(q.size()))

        jobs = []
        while q.next():
            id = q.value(0).toString()
            name = q.value(1).toString()
            description = q.value(2).toString()
            startTime = q.value(3).toUInt()
            if(startTime[1]):
                startTime = startTime[0]
            else:
                startTime = 0
            longTime = q.value(4).toUInt()
            if(longTime[1]):
                longTime = longTime[0]
            else:
                longTime = 0
            log.debug(str(id) + name + QtCore.QDateTime.fromTime_t(startTime).toString())
            jobs.append(Job(id, name, description, startTime, longTime))
        return jobs

    def dump(self):
        for i in self.getJobs():
            log.debug(str(i.id) + ", name=" + i.name + ", dscr=" + i.description + ", start on " + QtCore.QDateTime.fromTime_t(i.startTime).toString() + str(i.startTime))

    def addJob(self, job):
        id = -1

        q = QtSql.QSqlQuery(self.db)
        q.prepare("INSERT INTO jobs(name, description, startTime, longTime) VALUES(:name, :description, :startTime, :longTime);")
        q.bindValue(":name", job.name)
        q.bindValue(":description", job.description)
        q.bindValue(":startTime", job.startTime)
        q.bindValue(":longTime", job.longTime)
        ok = q.exec_()

        if not ok:
            raise DataBaseException("can't insert job")

        log.debug("q.lastInsertId()=" + q.lastInsertId().toString() + ", query=" + q.lastQuery())

        id = q.lastInsertId().toUInt()

        if id[1]:
            id = id[0]
        else:
            id = -1

        if id < 0:
            raise DataBaseException("can't get last inserted ID")

        job = Job(id, job.name, job.description, job.startTime, job.longTime)
        self.onJobAdded(job)
        return job

    def addListener(self, modelObject):
        self.listeners.append(modelObject)

    def onJobAdded(self, job):
        for i in self.listeners:
            i.onJobAdded(job)
